package com.feilx.changggou.seckill.common;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Configuration
public class RedissionLock {

    // 注册redission 使用分布式锁
    @Bean
    public Redisson redisson(){
        Config config = new Config();
        config.useClusterServers().addNodeAddress("redis://192.168.11.181:6379");
        return (Redisson) Redisson.create(config);
    }

    @Value("${cache.cluster0.password}")
    private String password;
    @Value("${cache.cluster0.nodes}")
    private String nodeConfig;

    @Bean
    public RedissonClient getRedisClient() {
        Config config = new Config();
        List<String> nodeList = null;
        if (this.nodeConfig != null) {
            nodeList = (List) Stream.of(this.nodeConfig.split(",")).map((str) -> {
                return "redis://" + str;
            }).collect(Collectors.toList());
            String p = "".equals(this.password) ? null : this.password;
            if (nodeList.size() == 1) {
                config.useSingleServer().setAddress((String)nodeList.get(0)).setPassword(p);
            } else {
                config.useClusterServers().setScanInterval(2000).addNodeAddress((String[])nodeList.toArray(new String[nodeList.size()])).setPassword(p);
            }

            return Redisson.create(config);
        } else {
            return null;
        }
    }
}
